package com.bdcom.autotest.interaction.step.remodel;

import com.bdcom.autotest.interaction.bean.DeviceUpdBean;
import com.bdcom.autotest.interaction.http.OperDevice;
import com.bdcom.autotest.interaction.http.callback.EnterMonitorCallBack;
import com.bdcom.autotest.interaction.socket.DataUtil;
import com.bdcom.autotest.interaction.step.IStepHandler;
import com.bdcom.autotest.interaction.step.StepThread;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class EnterMonitor implements IStepHandler{

	
	@Override
	public boolean runStep(StepThread mainrun) {
		boolean result = false;
		String[] sns = DataUtil.deleteArrayNull(mainrun.getMf().getLeftp().getsns());
//		mainrun.setFail(new ArrayList<>());
		mainrun.setFail(Arrays.asList(sns));
		if (!mainrun.isEndFlag()) {
			int repeatCount = mainrun.getCurrentStep().getRunTimes();
			if (repeatCount==0) {//非重试
				try {
					while (mainrun.getEnterMonitorResult().size() < sns.length) {
						Thread.sleep(200);
					}
				} catch (Exception e) {
				}
				result = isAllSuccess(mainrun);
			}else if(repeatCount<mainrun.getMaxRepeatCount()){//重试
				List<DeviceUpdBean> deviceUpdBeanList = mainrun.getEnterMonitorResult();
				mainrun.setEnterMonitorResult(new ArrayList<>());
				int failCount = 0;
				for (DeviceUpdBean bean : deviceUpdBeanList) {
					if (!bean.getMonitorFlag()) {//monitor失败的重试
						failCount++;
						EnterMonitorCallBack enterMonitorCallBack = new EnterMonitorCallBack(mainrun);
						OperDevice.enterMonitor(bean, enterMonitorCallBack);
					}
				}
				try {
					while (mainrun.getEnterMonitorResult().size() < failCount) {
						Thread.sleep(200);
					}
					result = isAllSuccess(mainrun);
				} catch (Exception e) {
				}
			}else{//超过重试次数往下走
				result = true;
			}
			mainrun.addLog("所有设备进入monitor结果统计：");
			List<String> macHasResult =new ArrayList<>();
			List<DeviceUpdBean> deviceUpdBeanList = mainrun.getEnterMonitorResult();
			for(DeviceUpdBean deviceUpdBean:deviceUpdBeanList){
				macHasResult.add(deviceUpdBean.getMac());
				if (!deviceUpdBean.getMonitorFlag()) {
					mainrun.addLog(deviceUpdBean.getMac()+"进入monitor失败");
				}else{
					mainrun.addLog(deviceUpdBean.getMac()+"进入monitor成功");
				}
			}
			for(String mac:sns){
				if(!"".equals(mac)){
					if(!macHasResult.contains(mac)){
						mainrun.addLog(mac+"进入monitor成功");
					}
				}
			}
		}
		return result;
//		return true;
	}

	private boolean isAllSuccess(StepThread mainrun){
		List<String> passCardSn = new ArrayList<>();
		List<DeviceUpdBean> deviceUpdBeanList = mainrun.getEnterMonitorResult();
		boolean result = true;
		for (DeviceUpdBean bean : deviceUpdBeanList) {
			if (!bean.getMonitorFlag()) {
				result = false;
			}else{
				passCardSn.add(bean.getMac());
			}
		}
		mainrun.setFail(passCardSn);
		return result;
	}
}
